<template>
	<div class="section"
		v-loading="loading.status"
		:element-loading-text="loading.txt"
	>
		<!--  -->
		<div class="pointMark_video">
			<template v-if="1">
				<video-player  class="video-player vjs-custom-skin"
					ref="videoPlayer"
					:playsinline="true"
					:options="playerOptions"
					@play="onPlayerPlay($event)"
					>
				</video-player>
			</template>
			<img v-else src="../../../public/images/image_couse2.png">
		</div>
		<div class="publishFrom">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<div class="publishFrom_if clear">
					<el-form-item label="开始时间" prop="start_time" class="publishFrom_if_l fl">
						<span>
							<el-time-picker
							   v-model="ruleForm.start_time"
							   value-format="HH:mm:ss"
							   :picker-options="{
							   	 format: 'HH:mm:ss',
							     selectableRange: timeMaxStart
							   }"
							   placeholder="任意时间点">
							 </el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlaySTime"></i>
					</el-form-item>
					<!--  -->
					<el-form-item label="结束时间" prop="end_time" class="publishFrom_if_l fr">
						<span>
							<el-time-picker
							   v-model="ruleForm.end_time"
							   value-format="HH:mm:ss"
							   :picker-options="{
							   	format: 'HH:mm:ss',
							     selectableRange: timeMaxEnd
							   }"
							   placeholder="任意时间点">
							 </el-time-picker>
						</span>
						<i class="el-icon-location"  @click="getVideoPlayETime"></i>
					</el-form-item>
				</div>
				<el-form-item label="视频切片" prop="name">
					<el-input v-model.trim="ruleForm.name" maxlength="20" placeholder="视频切片，最多可输入20个字"></el-input>
				</el-form-item>
				<el-form-item label="视频备注" prop="comment">
					<el-input v-model.trim="ruleForm.comment" maxlength="100" placeholder="切片备注，最多可输入100个字"></el-input>
				</el-form-item>
				<el-form-item class="buttonCSS publishFrom_btn" label-width="0" >
					<!-- <el-checkbox v-model="ruleForm.is_virtual">虚拟切片</el-checkbox> -->
					<!-- <el-checkbox v-model="ruleForm.is_micro">推送微课</el-checkbox> -->
					<!-- <el-button @click="resetForm('ruleForm')" type="primary" plain>取消</el-button> -->
					<el-tooltip class="item" effect="dark" content=" 切片大小请控制在4G以内，切片视频过大将影响切片等待时间和系统运行内存" placement="top-start">
					    <span class="slice-tips"><i class="el-icon-info"></i></span>
					   </el-tooltip>
					<el-button type="primary" @click="submitForm('ruleForm')">生成切片</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="publishFrom_table">
			<template>
				<el-table
				border
				:data="listData"
				style="width: 100%">
					<el-table-column
						prop="cut_name"
						label="切片名称"
						width="190"
						show-overflow-tooltip>
					</el-table-column>	
					<el-table-column
						prop="video_start_time"
						label="开始时间"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
						prop="video_end_time"
						label="结束时间"
						show-overflow-tooltip>
					</el-table-column>
					<!-- <el-table-column
						prop=""
						label="切片类型"
						width="80"
						show-overflow-tooltip>
						<template slot-scope="scope">
							{{ parseInt(scope.row.is_virtual) === 1 ? '虚拟切片' : '物理切片'}}
						</template>
					</el-table-column> -->
					<!-- <el-table-column
						prop=""
						label="是否微课"
						width="70">
						<template slot-scope="scope">
							{{ parseInt(scope.row.is_micro) === 1 ? '是' : '否'}}
						</template>
					</el-table-column> -->
					<el-table-column
						prop="comment"
						label="备注"
						width="100"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
						prop=""
						label="状态"
						align="center"
						show-overflow-tooltip
						width="100">
						<template slot-scope="scope">
							<span :class="scope.row.status == '切片失败' ? 'delete-button' : ''">{{scope.row.status}}</span>
						</template>
					</el-table-column>
					<el-table-column
					    label="操作"
					    align="center"
					    width="100"
					    show-overflow-tooltip>
					    <template slot-scope="scope">
					    	<el-button v-if="scope.row.status == '正常切片'" @click="videoView(scope.row)" type="text">预览</el-button>
					     	<el-button @click="deleteCut(scope.row)" type="text" size="small">删除</el-button>
					    </template>
					  </el-table-column>
				</el-table>
			</template>
			<!--  -->
			<div class="pageBox" v-if="total_number > listParam.page_size">
				<el-pagination
				    @size-change="handleSizeChange"
				    @current-change="handleCurrentChange"
				    :current-page="listParam.page_index"
				    :page-size="listParam.page_size"
				    layout="total,  prev, pager, next, jumper"
				    :total="total_number">
				</el-pagination>
			</div>
		</div>
		<transition name="el-fade-in-linear" >
			<div class="masking" :class="{ activeLive: isActive }">
				<div class="maskingBox">
					<div class="masking_h clear">
						<span>切片预览</span>
						<i class="el-icon-close fr" @click="viewClose"></i>
					</div>
					<div class="masking_c">
						<videoAlertView  v-if="showVideoPlayer" :playParam.sync="playParam" >
						</videoAlertView>

					</div>
				</div>
			</div>
		</transition>


	</div>
</template>
<script>
	import videoAlertView from './videoAlertView'
	// import SWF_URL from 'videojs-swf/dist/video-js.swf';
	export default {
		props : ['compParam','activeIndex'],
		name: '',
		data() {
			return {
				thisIndex:'4',
				total_number:0,
				loading:{
					status:false,
					txt:'获取数据...'
				},
				timeMaxStart: '00:00:00 - 00:00:00',
				timeMaxEnd: '00:00:00 - 00:00:00',
				currentPage4: 4,
				ruleForm: {
					slice: '', //开始时间
					remarks:'', //视频备注
					end_time: '', //结束时间
					start_time: '', //开始时间
					is_virtual: false, //虚拟切片
					is_micro: false, //推送微课

				},
				listData:[],
				listParam:{
					video_id:0,
					page_index:1,
					page_size:10,
				},
				rules: {
					name: [
						{ required: true, message: '请输入视频切片名称', trigger: 'blur' },
						// { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					comment: [
						{ required: false, message: '请输入视频备注', trigger: 'blur' },
						// { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					start_time: [
						{ required: true, message: '请输入开始时间', trigger: 'blur' },
					],
					end_time: [
						{ required: true, message: '请输入结束时间', trigger: 'blur' },
					]
				},
				playerOptions : {
				    loop: false,
				    height: '360',
			        sources: [{
			            type: "application/x-mpegURL",
			            src: "blabla"
			        }],
			        // techOrder: ['flash'],
			        autoplay: false,
			        controls: true,
			        poster: "",
					controlBar: {
			          	timeDivider: true,
			         	durationDisplay: true,
			         	remainingTimeDisplay: false,
			          	fullscreenToggle: true  //全屏按钮
				    },
				    // flash: {swf: SWF_URL },
				},
				tableData: [],

				isActive: false,
				showVideoPlayer:false,
				playParam:{play_url:'',start_time:null,end_time:null},
				// sliceView: false

			}
		},
		computed: {
			videoId(){
				return this.compParam.id;
			}
		},
		watch:{
			
	    	'videoId':{
	    		handler(n){
	    			this.initFunc();
	    		},
	    		deep:true
	    	},
	    	
		},
		mounted(){
			this.initFunc();
		},
		beforeDestroy(){
			this.$refs.videoPlayer && this.$refs.videoPlayer.player.reset()
		},
		methods: {
			//视频
			// listen event
			onPlayerPlay(player) {
				this.onSlicePlay()
			},
			/**
			 * 改变进度条
			 */
			onSlicePlay() {
			  /*  this.debounce(() => {
			        var normal_currentTime = this.$refs.videoPlayer.player.currentTime();
			        var unnormal_currentTime = this.$refs.videoPlayer.player.currentTime();
			        if (
			            normal_currentTime.toString() ==
			            unnormal_currentTime.toString()
			        ) {
			            this.$refs.videoPlayer.player.pause();
			            this.$refs.videoPlayer.player.play();
			        }
			    }, 100);*/

			},
			//延迟处理
			debounce(func, wait, immediate) {
			    let timeout, args, context, timestamp, result;
			    const later = function() {
			        // 据上一次触发时间间隔
			        const last = +new Date() - timestamp;

			        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
			        if (last < wait && last > 0) {
			            timeout = setTimeout(later, wait - last);
			        } else {
			            timeout = null;
			            // 如果设定为immediate===true，因为开始已经调用过了此处无需调用
			            if (!immediate) {
			                result = func.apply(context, args);
			                if (!timeout) context = args = null;
			            }
			        }
			    };
			    return function(...args) {
			        context = this;
			        timestamp = +new Date();
			        const callNow = immediate && !timeout;
			        // 如果延时不存在，重新设定延时
			        if (!timeout) timeout = setTimeout(later, wait);
			        if (callNow) {
			            result = func.apply(context, args);
			            context = args = null;
			        }

			        return result;
			    };
			},
			initFunc(){
				this.$refs.videoPlayer.player.src({ type : "application/x-mpegURL", src : this.compParam.play_url }) ;
				this.timeMaxStart = '00:00:00 - '+this.compParam.length;
				this.timeMaxEnd =  '00:00:00 - '+this.compParam.length;
				this.getCutList();
			},
			viewClose(){
				this.showVideoPlayer = false;
				this.isActive = false
			},
			videoView(obj){
				this.playParam.play_url = obj.pc_play_cut_url;
				if( obj.is_virtual === 1 ){
					this.playParam.start_time = obj.start_time ;
					this.playParam.end_time = obj.end_time ;
				}else{
					this.playParam.start_time = null ; 
					this.playParam.end_time = null ; 
				}
				this.showVideoPlayer = true;
				this.isActive = true
				// this.sliceView = true
			},
			saveCut(){
				this.loading.status = true;
				this.loading.txt = '保存数据...';
				var start_time = this.ruleForm.start_time.split( ":" ); // 时间字符分割 
				var end_time = this.ruleForm.end_time.split( ":" ); // 时间字符分割 
				var start_timeSeconds = parseInt( start_time[ 0 ] * 3600 ) + parseInt( start_time[ 1 ] * 60 ) + parseInt( start_time[ 2 ] ); // 时间转成秒数
				var end_timeSeconds = parseInt( end_time[ 0 ] * 3600 ) + parseInt( end_time[ 1 ] * 60 ) + parseInt( end_time[ 2 ] ); // 时间转成秒数

				var params = {
					video_id : this.compParam.id,
					name:this.ruleForm.name,
					comment : this.ruleForm.comment,
					start_time : start_timeSeconds,
					end_time : end_timeSeconds,
					is_virtual:this.ruleForm.is_virtual? 1 : 0,
					is_micro:this.ruleForm.is_micro? 1 : 0
				}

				let success = (data=>{
					this.loading.status = false;
					this.$message.success(data.msg)
					this.initFunc();
					this.resetForm('ruleForm');
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
				})
				this.$ajax.post('api/video/video_cut',params,{func:{success:success,fail:fail}})
			},
			deleteCut( obj ){
				let yes = ( data => {
					let success = ( data => {
						if(this.listData.length > 0 && this.listParam.page_index > 1){
							this.listParam.page_index--;
						}
						this.getCutList();
						this.$message.success(data.msg)
					})
					this.$ajax.delete('api/video/video_cut',{params: {id:obj.cut_id},func:{success:success}})
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.cut_name+' 删除吗？'});
			},
			//视频信息
			getCutList(){
				this.loading.status = true;
				this.loading.txt = '获取数据...';
				this.listParam.video_id = this.compParam.id;
				if( is_empty( this.compParam.id ) || parseInt(this.compParam.id ) === 0 ){
					this.loading.status = false;
					this.total_number = 0;
					this.listData = []
					return false;
				}
				let success = (data=>{
					this.loading.status = false;
					this.total_number = data.data.data_sum;
					this.listData = data.data.data
					for (var i = this.listData.length - 1; i >= 0; i--) {
						var newTime = formatSeconds(this.listData[i].video_time);
						this.listData[i].video_time = newTime.hour+':'+newTime.minute+':'+newTime.second
					}
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
				})
				this.$ajax.get('api/video/video_cut_list',{params: this.listParam,func:{success:success}})
			},
			getVideoPlaySTime(){
				var nowTime = formatSeconds(this.$refs.videoPlayer.player.currentTime());
				this.ruleForm.start_time = nowTime.hour+':'+nowTime.minute+':'+nowTime.second
			},
			getVideoPlayETime(){
				var nowTime = formatSeconds(this.$refs.videoPlayer.player.currentTime());
				this.ruleForm.end_time = nowTime.hour+':'+nowTime.minute+':'+nowTime.second
			},
			handleSizeChange(val) {
		    	this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getCutList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getCutList();
		    },
			//表单验证
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.saveCut();
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
		},
		components: {
		 	videoAlertView
		}
	}
</script>